var express = require('express');
var router = express.Router();
const auth = require('../modules/auth');
const query = require('../modules/query');

//router.post('/', auth.verifyToken)
/**
 * 模拟验证请求
 */
router.post('/test', auth.verifyToken, function (req, res, next) {
  setTimeout(() => {
    res.send({
      code: 0,
      msg: 'test操作成功'
    });
  }, 300);
});
/**
 * 回环测试
 */
router.post('/testback', function (req, res, next) {
  setTimeout(() => {
    res.send(req.body);
  }, 300);
});
/**
 * 设置课程信息
 */
router.post('/setlesson', auth.verifyToken, function (req, res, next) {
  console.log(req.body);
  query.setLesson(req.body)
    .then(() => {
      console.log("set lesson success");
      res.send({
        code: 0,
        msg:"执行成功"
      })
    })
    .catch(err => {
      res.status(401).send({
        code: 3,
        msg: '数据库操作失败'
      });
    })
});
/**
 * 获取课程信息
 */
router.post('/getlesson',auth.verifyToken, function (req, res, next) {
  query.getLesson()
  .then(data => {
    res.send(data);
  })
  .catch(err => {
    console.log(err);
  })
})

// var crypto = require('crypto');
// var sha256 = crypto.createHash('sha256');

// function calcUserHash(user) {
//   sha256.update(user.username.split('').reverse().join(''));
//   sha256.update(user.password);
//   return sha256.digest("hex");
// }

/* 登录post */
router.post('/login', async function (req, res, next) {
  const user = {
    username: req.body.username,
    password: req.body.password
  }
  //从数据库匹配用户名和密码
  let userInfo = await auth.verifyUser(user.username, user.password);
  if (!userInfo) {
    //匹配失败
    res.status(401).send({
      code: 2,
      msg: '用户名或密码错误'
    });
    return;
  }
  //生成token,使用用户id
  userInfo.token = auth.sign(user.username);
  userInfo.code = 0;
  userInfo.msg = '登录成功';
  console.log(userInfo);
  res.send(userInfo);
});

/**
 * 检查token是否需要更新
 */
router.post('/checktoken', function (req, res, next) {
  try {
    const tokenData = auth.checkTokenTimeout(req.body.token)
    console.log(tokenData)
    res.send(tokenData);
  } catch (error) {
    res.status(401).send({
      code: 1,
      msg: 'Token错误'
    });
  }
});
/**
 * 退出登录
 */
router.post('/logout', function (req, res, next) {
  try {
    auth.logout(req.body.token)
    res.send({
      code: 0,
      msg: '注销成功'
    });
  } catch (error) {
    res.status(401).send({
      code: 1,
      msg: 'Token错误'
    });
  }
});

module.exports = router;